package com.sl.u_push_plugin

import android.content.Context
import android.util.Log
import android.widget.Toast
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import com.umeng.message.UmengNotificationClickHandler
import com.umeng.message.entity.UMessage
import io.flutter.plugin.common.EventChannel


class PushManager private constructor() {

    private var context: Context? = null
    private var deviceToken: String? = null
    var events: EventChannel.EventSink? = null
    val pushInstance by lazy {
        PushAgent.getInstance(context)
    }

    fun initEvents(events: EventChannel.EventSink?) {
        this.events = events
    }


    companion object {
        val instance by lazy {
            PushManager()
        }
    }

    fun initContext(context: Context?) {
        this.context = context
    }

    fun pushRegister() {
        pushInstance.register(object : IUmengRegisterCallback {
            override fun onSuccess(p0: String?) {
                Log.e(Tag.SLUPushError, "注册成功：deviceToken：-------->  " + p0);
                deviceToken = p0;
//                initUMengMessagePushService()
//                result.success(mapOf("resCode" to 0, "resValue" to p0))
//                Observable.just(p0).observeOn(AndroidSchedulers.mainThread()).subscribe {
//                    result.success(mapOf("resCode" to 0, "resValue" to p0))
//                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Log.e(Tag.SLUPushError, "注册失败：deviceToken：-------->  " + "s:" + p0 + ",s1:" + p1)
//                Observable.just(mapOf("value" to p0, "reason" to p1)).observeOn(AndroidSchedulers.mainThread()).subscribe {
//                    result.success(mapOf("resCode" to -1, "resValue" to "error : $p0 , reason :$p1"))
//                }
            }
        })
    }

    fun appStart(context: Context) {
        PushAgent.getInstance(context).onAppStart();
    }

    fun initUPush(context: Context, appKey: String, appSecretKey: String) {
        UMConfigure.init(context, appKey, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, appSecretKey);
        UMConfigure.setLogEnabled(true)

        PushAgent.getInstance(context).register(object : IUmengRegisterCallback {
            override fun onSuccess(p0: String?) {
                if (events == null) {
                    Log.e(Tag.SLUPushError, "flutter 未完成 注册，无法发送消息，请使用get方法获取")
                }

                deviceToken = p0
                var result = ResaultData().Builder().initData("code", 1).initData("value", p0
                        ?: "").initType(TypeData.login).build()
                events?.run {
                    success(result)
                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Log.e(Tag.SLUPushError, "注册失败：deviceToken：-------->  " + "s:" + p0 + ",s1:" + p1)
                var result = ResaultData().Builder().initData("code", -1).initData("value", "code:$p0,error:$p1").initType(TypeData.login).build()
                events?.run {
                    success(result)
                }
            }
        })
        PushAgent.getInstance(context).onAppStart()
        val notificationClickHandler: UmengNotificationClickHandler = object : UmengNotificationClickHandler() {
            override fun launchApp(context: Context, msg: UMessage) {
                super.launchApp(context, msg)
                sendClickData(msg)
            }

            override fun openUrl(context: Context, msg: UMessage) {
                super.openUrl(context, msg)
                sendClickData(msg)
            }

            override fun openActivity(context: Context, msg: UMessage) {
                super.openActivity(context, msg)
                sendClickData(msg)
            }

            override fun dealWithCustomAction(context: Context, msg: UMessage) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show()
            }
        }
        PushAgent.getInstance(context).notificationClickHandler = notificationClickHandler
    }

    private fun sendClickData(uMessage: UMessage) {
        var result = ResaultData().Builder()
        uMessage.extra?.forEach {
            result.initData(it.key, it.value)
        }
        result.initType(TypeData.message);
        events?.success(result.build())
    }

    ///应用前台是否显示通知
    fun changeShowNotificaitonOnForeground(show: Boolean) {
        pushInstance.setNotificaitonOnForeground(show)
    }

    fun setNoDisturbMode(startHour: Int, endHour: Int, startMin: Int, endMin: Int) {
        pushInstance.setNoDisturbMode(startHour, startMin, endHour, endMin)
    }

    fun initUMengMessagePushService() {
        pushInstance.setPushIntentServiceClass(UMessagePushService::class.java)
    }

    fun getPushDeviceToken(): String {
        return deviceToken ?: ""
    }

}